package com.ftl.search.common.interceptor;

import com.ftl.search.common.aop.JwtIgnore;
import com.ftl.search.common.context.LoginUserContext;
import com.ftl.search.common.property.JwtProperties;
import com.ftl.search.common.utils.JwtTokenProvider;
import com.ftl.search.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.invoke.MethodHandle;

@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Resource
    private JwtProperties jwtProperties;

    @Resource
    private JwtTokenProvider jwtTokenProvider;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 忽略带JwtIgnore注解的请求，不做后续token认证校验
        if (handler instanceof MethodHandle) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            JwtIgnore jwtIgnore = handlerMethod.getMethodAnnotation(JwtIgnore.class);
            if (jwtIgnore != null) {
                return true;
            }
        }
        if (HttpMethod.OPTIONS.name().equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        final String authHeader = request.getHeader(jwtProperties.getAuthKey());
        if (!StringUtils.hasText(authHeader)) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "missing token");
            return false;
        }
        final String token = authHeader.trim().replace("Bearer ", "");
        User user = jwtTokenProvider.resolveToken(token);
        LoginUserContext.setLoginUser(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("remove User ----------------- {}", LoginUserContext.getLoginUser());
        LoginUserContext.remove();
    }
}
